package com.cmii.sjw.department.control.jsc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmii.sjw.department.control.jsc.mapper.ActivityCodeMapper;
import com.cmii.sjw.department.control.jsc.mapper.TrainingParticipantsMapper;
import com.cmii.sjw.department.control.jsc.mapper.TrainingUniversitiesMapper;
import com.cmii.sjw.department.control.jsc.model.ActivityCode;
import com.cmii.sjw.department.control.jsc.model.dto.TrainingParticipantsDTO;
import com.cmii.sjw.department.control.jsc.model.entity.TrainingParticipants;
import com.cmii.sjw.department.control.jsc.model.entity.TrainingUniversities;
import com.cmii.sjw.department.control.jsc.service.TrainingService;
import com.cmii.sjw.department.control.jsc.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class TrainingServiceImpl implements TrainingService {

    @Autowired
    private TrainingParticipantsMapper trainingParticipantsMapper;

    @Autowired
    private TrainingUniversitiesMapper trainingUniversitiesMapper;

    @Autowired
    private ActivityCodeMapper activityCodeMapper;

    @Override
    public Result<List<TrainingUniversities>> universitiesList() {
        List<TrainingUniversities> list = trainingUniversitiesMapper.selectList(
                new QueryWrapper<TrainingUniversities>()
                        .orderByAsc("sort_order")
        );
        return  Result.success(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<String> saveTrainingParticipants(List<TrainingParticipantsDTO> tpds) {
        List<TrainingParticipants> list = new ArrayList<>(tpds.size());

        for (TrainingParticipantsDTO tpd : tpds) {
            Result<String> validationResult = validateParticipant(tpd);
            if (validationResult.getCode() != 200) {
                return validationResult;
            }

            TrainingParticipants tp = new TrainingParticipants();
            BeanUtils.copyProperties(tpd, tp);
            list.add(tp);
        }

        try {
            trainingParticipantsMapper.insertBatch(list);
            return Result.success("保存成功");
        } catch (Exception e) {
            log.error("保存参训人员失败", e);
            return Result.error("保存失败");
        }
    }

    @Override
    public Result<List<ActivityCode>> getUniversitiesAuthCode(String universitiesName) {
        List<ActivityCode> activityCodeList = activityCodeMapper.selectList(
                new QueryWrapper<ActivityCode>()
                        .eq("school_name", universitiesName)
        );
        return Result.success(activityCodeList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> createUniversitiesAuthCode(ActivityCode params) {
        long count = activityCodeMapper.selectCount( new QueryWrapper<ActivityCode>()
                .eq("school_name", params.getSchoolName())
                .eq("application_system_name", params.getApplicationSystemName())
        );
        if (count > 0) {
            return Result.error(params.getSchoolName()+params.getApplicationSystemName()+"系统的授权码已存在");
        }
        params.setAuthCode((generateRandomString(21)));
        try {
            activityCodeMapper.insert(params);
            return Result.success("创建成功");
        } catch (Exception e) {
            log.error("创建授权码失败", e);
            return Result.error("创建失败");
        }
    }

    private Result<String> validateParticipant(TrainingParticipantsDTO tpd) {
        if (tpd.getUniversityId() == null) {
            return Result.error("高校选项不能为空");
        }
        if (tpd.getIsLeader() == null) {
            return Result.error("是否负责人不能为空");
        }
        if (StringUtils.isEmpty(tpd.getName())) {
            return Result.error("名称不能为空");
        }
        if (StringUtils.isEmpty(tpd.getPosition())) {
            return Result.error("职位不能为空");
        }

        // 数据部门 负责人验证
        if (tpd.getIsLeader() == 0) {
            if (StringUtils.isEmpty(tpd.getIdCard())) {
                return Result.error("身份证号不能为空");
            }
            if (StringUtils.isEmpty(tpd.getPhone())) {
                return Result.error("手机号不能为空");
            }
        }
        if (StringUtils.isNotEmpty(tpd.getIdCard())) {
            // 检查身份证号是否重复
            QueryWrapper<TrainingParticipants> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id_card", tpd.getIdCard());
            if (trainingParticipantsMapper.selectCount(queryWrapper) > 0) {
                return Result.error("身份证号重复");
            }
        }
        QueryWrapper<TrainingUniversities> universitiesWrapper = new QueryWrapper<>();
        universitiesWrapper.eq("id", tpd.getUniversityId());
        if (trainingUniversitiesMapper.selectCount(universitiesWrapper) == 0) {
            return Result.error("高校选项不存在");
        }
        return Result.success();
    }

    public static String generateRandomString(int length) {
        String randomString = UUID.randomUUID().toString();
        randomString = randomString.replace("-", "");
        return randomString.substring(0, length);
    }


}
